<?php
/**
 * Created by PhpStorm.
 * User: z-benjamin
 * Date: 16/9/9
 * Time: 上午11:49
 */

namespace wxml\models\user;

use Yii;
use wxml\libs\CommonModel;
use wxml\models\user\AR\UserAR;

class User extends CommonModel{



    public function checkAccessToken($user_id,$access_token){
        $user=UserAR::findOne(['id'=>$user_id]);

        if($user){
            if($user->status==0){
                $this->setError(-998,"该账号已被禁用");
                return false;
            }
            if($access_token<>$user->access_token){
                $this->setError(-999,"登录信息已失效,请重新登录!");
                return false;
            }
            if(strtotime($user->expire)<date('Y-m-d H:i:s')){
                $this->setError(-999,"登录信息已失效,请重新登录!");
                return false;
            }

            return true;
        }else{
            $this->setError(-999,"用户信息异常!");
            return false;
        }
    }

    public function register($loginUser){
        $user=UserAR::findOne(['name'=>$loginUser['username']]);

        if($user){
            $this->setError(-1,"用户名已存在!");
            return false;
        }
        $user=UserAR::findOne(['mobile'=>$loginUser['mobile']]);
        if($user){
            $this->setError(-1,"该手机号已注册!");
            return false;
        }
        $user=new UserAR();
        $user->name=$loginUser['username'];
        $user->mobile=$loginUser['mobile'];
        $user->password=md5(md5($loginUser['password']));
        $user->status=1;
        $res=$user->save();
        if($res){
            return $user;
        }else{
            $this->setError(-1,"保存用户信息失败!");
            return false;
        }
    }

    public function login($username,$password){
        $user=UserAR::find()->andWhere(['name'=>$username])->orWhere(['mobile'=>$username])->one();
        if($user){
            if($user->password!==md5(md5($password))){
                $this->setError(-1,"用户名或密码错误");
                return false;
            }
            if($user->status==0){
                $this->setError(-998,"该账号已被禁用");
                return false;
            }
            $user->access_token=md5("LV".time());
            $user->login_time=date('Y-m-d H:i:s');
            $user->expire=date('Y-m-d H:i:s',strtotime('+1 day'));
            $res=$user->save();
            if($res){
                unset($user->password);
                unset($user->paypassword);
                return $user;
            }else{
                $this->setError(-1,"保存用户信息失败!");
                return false;
            }
        }else{
            $this->setError(-1,"用户名或密码错误!");
            return false;
        }
    }
}